package com.luyang.framework.protocol.configuration;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.luyang.framework.protocol.interceptor.SqlLogInterceptor;
import com.luyang.framework.validator.factory.YamlPropertySourceFactory;
import org.apache.ibatis.type.EnumTypeHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * MP 配置
 *
 * @author lu_yang
 */
@EnableTransactionManagement
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration(proxyBeanMethods = false)
@MapperScan("com.luyang.**.dao.**")
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:luyang-mp.yml")
public class MybatisPlusConfiguration {

    /**
     * IEnum 枚举配置
     *
     * @return com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer
     * @author lu_yang
     */
    public @Bean ConfigurationCustomizer configurationCustomizer() {
        return config -> {
            // 配置全局默认枚举类型处理器
            config.setDefaultEnumTypeHandler(EnumTypeHandler.class);
            config.setLogPrefix("log.mybatis");
        };
    }

    /**
     * 乐观锁拦截器
     *
     * @return com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor
     * @author lu_yang
     */
    public @Bean OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
        return new OptimisticLockerInnerInterceptor();
    }

    /**
     * 打印 SQL 语句和执行时间
     *
     * @return com.luyang.framework.mybatis.interceptor.SqlLogInterceptor
     * @author lu_yang
     */
    @Profile({"dev", "sit", "uat"})
    // @ConditionalOnProperty(value = "luyang.mybatis-log.enable", matchIfMissing = true)
    @ConditionalOnProperty(prefix = "luyang.mybatis-log", name = "enable", havingValue = "true")
    public @Bean
    SqlLogInterceptor sqlLogInterceptor() {
        return new SqlLogInterceptor();
    }
}
